<!-- 设置 -->

<template>
    <PageTable ref="pageTableRef" :headers="tableHeaders" allow-search :search-form="searchForm"
        :loadCallable="loadCallable" :btns="btns">
    </PageTable>


    <!-- BEGIN 新增弹框 -->
    <el-dialog v-model="addSettingForm.showDialog" :draggable="true" header="新增设置项">
        <el-form ref="addSettingFormRef" :model="addSettingForm.formData" :rules="addSettingForm.rules" label-width="auto">

            <el-form-item label="配置名称" prop="name">
                <el-input v-model="addSettingForm.formData.name" name="name"></el-input>
            </el-form-item>

            <el-form-item label="唯一标识" prop="code">
                <el-input v-model="addSettingForm.formData.code" name="code" placeholder="全局唯一,中英文、数字、-_"></el-input>
            </el-form-item>

            <el-form-item label="值" prop="val">
                <el-input v-model="addSettingForm.formData.val" name="val"></el-input>
            </el-form-item>

            <el-form-item label="表单类型" prop="input_type">
                <el-select v-model="addSettingForm.formData.input_type">
                    <el-option v-for="(text, typ) in inputTypeObj" :key="typ" :label="text" :value="typ"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="额外数据" prop="ext">
                <el-input type="textarea" v-model="addSettingForm.formData.ext" name="ext"
                    placeholder="留空或者json"></el-input>
            </el-form-item>


            <el-button type="primary" @click="onAddSubmit(addSettingFormRef)">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 新增弹框  -->

    <!-- BEGIN 编辑弹框 -->

    <el-dialog v-model="editSettingForm.showDialog" :draggable="true" header="编辑">
        <el-form ref="editSettingFormRef" :model="editSettingForm.formData" :rules="editSettingForm.rules"
            label-width="auto">
            <el-input v-model="editSettingForm.formData.id" type="hidden"></el-input>

            <el-form-item label="配置名称" prop="name">
                <el-input v-model="editSettingForm.formData.name"></el-input>
            </el-form-item>

            <el-form-item label="唯一标识" prop="code">
                <el-input v-model="editSettingForm.formData.code" readonly></el-input>
            </el-form-item>

            <!-- BEGIN 值的渲染方式 -->

            <el-form-item v-if="editSettingForm.formData.input_type == SettingCode.INPUT_TYPE_TEXT" label="值" prop="val">
                <el-input v-model="editSettingForm.formData.val"></el-input>
            </el-form-item>
            <el-form-item v-if="editSettingForm.formData.input_type == SettingCode.INPUT_TYPE_TEXTAREA" label="值" prop="val">
                <el-input type="textarea" v-model="editSettingForm.formData.val"></el-input>
            </el-form-item>

            <el-form-item v-if="editSettingForm.formData.input_type == SettingCode.INPUT_TYPE_RADIO" label="值" prop="val">
                <el-radio-group v-model="editSettingForm.formData.val">
                    <el-radio v-for="(label, v) in editSettingForm.formData.ext.options"
                    :label="v">{{ label }}</el-radio>

                </el-radio-group>
            </el-form-item>

            <el-form-item v-if="editSettingForm.formData.input_type == SettingCode.INPUT_TYPE_CHECKBOX" label="值" prop="val">
                <el-checkbox-group @change="editFormCheckboxChange" v-model="editSettingForm.formData.checkList">
                    <el-checkbox v-for="(label, v) in editSettingForm.formData.ext.options"
                    :label="v" >{{ label }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item v-if="editSettingForm.formData.input_type == SettingCode.INPUT_TYPE_SELECT" label="值" prop="val">
                <el-select v-model="editSettingForm.formData.val">
                    <el-option v-for="(label, v) in editSettingForm.formData.ext.options" 
                    :key="v"
                    :label="label"
                    :value="v"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item v-if="editSettingForm.formData.input_type == SettingCode.INPUT_TYPE_SWITCH" label="值" prop="val">
                <el-switch v-model="editSettingForm.formData.val" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    :active-value="CommonCode.ON" :inactive-value="CommonCode.OFF" />
            </el-form-item>

            <!-- END 值的渲染方式  -->

            <el-button type="primary" @click="onEditSubmit">提交</el-button>
        </el-form>
    </el-dialog>
    <!-- END 编辑弹框  -->
</template>

<script setup>
import { ref } from 'vue'
import PageTable from '@/components/PageTable.vue';
import msgUtil from '@/utils/msgUtil'
import SettingCode from '@/constants/SettingCode';
import CommonCode from '@/constants/CommonCode'

import str from '@/utils/str'
import arr from '@/utils/arr'

import settingApi from '@/api/setting'

// pagetable的引用
const pageTableRef = ref();

// 新增设置formDom
const addSettingFormRef = ref()

// 表单类型
const inputTypeObj = SettingCode.textOfInputType()

// 开关常量
const switchConstArr = CommonCode.textOfSwitch();

const tableHeaders = [
    {
        prop: 'id',
        label: 'ID',
        width: 50
    },
    {
        prop: 'name',
        label: '配置名称',
    },
    {
        prop: 'code',
        label: '唯一标识',
    },
    {
        prop: 'val',
        label: '值',
        template(row) {
            if(row.input_type == SettingCode.INPUT_TYPE_SWITCH){
                return CommonCode.textOfSwitch(row.val)
            }else if(row.input_type == SettingCode.INPUT_TYPE_SELECT){
                return arr.get(row.ext?.options,row.val)
            }else if(row.input_type == SettingCode.INPUT_TYPE_RADIO){
                return arr.get(row.ext?.options,row.val)
            }
            else if(row.input_type == SettingCode.INPUT_TYPE_CHECKBOX){
                
                let t = [];
                row.val.split(',').forEach((item)=>{
                    let _t = arr.get(row.ext?.options, item);
                    if(_t){
                        t.push(_t);
                    }
                })

                return t.join(',')

            }
            return row.val;
        },
    },
]
const btns = {
    deleteAll: {
        text: '',
        click(ids) {
            settingApi.del(ids).then(res => {
                msgUtil.handleApiRes(res, {
                    onApiSuccess() {
                        pageTableRef.value.initPageData();
                    }
                });
            })
        }
    },
    add: {
        text: '',
        click() {
            showaddSettingForm()
        }
    },
    tableHeaderBtns: [
        {
            type: 'warning',
            text: '刷新缓存',
            click() {
                settingApi.refreshAll().then(res => {
                    msgUtil.showSuccessAndAlertError(res);
                })
            }
        }
    ],
    rowBtns: [{
        text: '编辑',
        click(rows, idx) {
            // 渲染默认值
            rendereditSettingFormData(rows)
            editSettingForm.value.showDialog = true
        },
    },]
};
const searchForm = ref({
    formItems: [
        {
            name: 's_name',
            type: 'text',
            placeholder: '配置名称',
        },
        {
            name: 's_code',
            type: 'text',
            placeholder: '唯一标识',
        },
    ]
})

const loadCallable = settingApi.pageList;

// 渲染默认编辑表单
function rendereditSettingFormData(row) {
    let rend = {
        id: row.id,
        pid : row.pid,
        sort : row.sort,
        name: row.name,
        code: row.code,
        val: row.val,
        input_type:row.input_type,
        ext: row.ext,
    };
    if(row.input_type == SettingCode.INPUT_TYPE_CHECKBOX){
        rend.checkList = row.val.split(',')
    }
    editSettingForm.value.formData = rend
}

// 修改值的checkbox改变
function editFormCheckboxChange(){
    editSettingForm.value.formData.val = editSettingForm.value.formData.checkList.join(',')
}

const resetaddSettingFormData = () => {
    return {
        name: '',
        code: '',
        val: '',
        ext: '',
        input_type: SettingCode.INPUT_TYPE_TEXT,
        pid: 0,
        sort: 0,
    }
}

function showaddSettingForm() {
    addSettingForm.value.formData = resetaddSettingFormData();
    addSettingForm.value.showDialog = true
}

// 新增表单
const addSettingForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: resetaddSettingFormData(),
    rules: {
        name: [
            { required: true, message: '必填', type: 'string' }
        ],
        code: [
            { required: true, message: '必填', type: 'string' }
        ],
        input_type: [
            { required: true, message: '必填', type: 'string' }
        ],
        val: [
            { required: true, message: '必填', type: 'string', },
        ],
        ext: [
            {
                trigger : "blur",
                validator: (rule, value, cb) => {

                    if (value === '') {
                        cb();
                    } else {
                        if (str.isJson(value)) {
                            cb()
                        } else {
                            cb(new Error('json格式错误'))

                        }
                    }
                }
            }
        ]
    }
})

// 提交新增
function onAddSubmit(formEl) {
    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (addSettingForm.value.onSubmiting) {
            return;
        }
        addSettingForm.value.onSubmiting = true;
        settingApi.add(addSettingForm.value.formData)
            .then(res => {
                msgUtil.handleApiRes(res, {
                    onApiSuccess() {
                        addSettingForm.value.showDialog = false
                        pageTableRef.value.initPageData();
                    }
                })
            })
            .finally(() => {
                addSettingForm.value.onSubmiting = false;
            })
    })

}

// 编辑管理员表单
const editSettingForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: {
        id: '',
        name: '',
        code: '',
        val: '',
        input_type : 'text',
        ext : {}
    },
    rules: {}
})

// 提交编辑
function onEditSubmit() {
    if (editSettingForm.value.onSubmiting) {
        return;
    }
    editSettingForm.value.onSubmiting = true
    settingApi.update(editSettingForm.value.formData).then(res => {
        msgUtil.showSuccessAndAlertError(res).then(() => {
            editSettingForm.value.showDialog = false;
            pageTableRef.value.initPageData();

        });
    }).finally(() => {
        editSettingForm.value.onSubmiting = false
    })

}
</script>